package com.atguigu.yygh.order.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.enums.PaymentTypeEnum;
import com.atguigu.yygh.enums.RefundStatusEnum;
import com.atguigu.yygh.model.order.OrderInfo;
import com.atguigu.yygh.model.order.PaymentInfo;
import com.atguigu.yygh.model.order.RefundInfo;
import com.atguigu.yygh.order.api.WxPayConfig;
import com.atguigu.yygh.order.service.OrderInfoService;
import com.atguigu.yygh.order.service.PaymentInfoService;
import com.atguigu.yygh.order.service.RefundInfoService;
import com.atguigu.yygh.order.service.WeixinService;
import com.atguigu.yygh.order.utils.HttpClient;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author 孔德成
 * @slogan 致敬大师，致敬未来的你
 * @date 2021/9/14 9:26 下午
 * @desc 微信 native 支付文档 https://pay.weixin.qq.com/wiki/doc/api/native.php?chapter=6_1
 */
@Service
public class WeixinServiceImpl implements WeixinService {

    @Autowired // 这里使用构造器注入会导致循环引用，无法启动服务
    private OrderInfoService orderService;
    private final PaymentInfoService paymentService;
    private final RefundInfoService refundInfoService;
    private final RedisTemplate redisTemplate;
    private final WxPayConfig wxPayConfig;

    public WeixinServiceImpl(PaymentInfoService paymentService, RefundInfoService refundInfoService, RedisTemplate redisTemplate, WxPayConfig wxPayConfig) {
        this.paymentService = paymentService;
        this.refundInfoService = refundInfoService;
        this.redisTemplate = redisTemplate;
        this.wxPayConfig = wxPayConfig;
    }


    /**
     * 商户后台系统先调用微信支付的统一下单接口，微信后台系统返回链接参数code_url，
     * 商户后台系统将code_url值生成二维码图片，用户使用微信客户端扫码后发起支付。
     * 注意：code_url有效期为2小时，过期后扫码不能再发起支付。
     *
     * @param orderId
     * @return
     */
    @Override
    public Map createNative(Long orderId) {
        try {
            // 1. 查询 redis 中是否有未支付的交易订单
            Map payMap = (Map) redisTemplate.opsForValue().get(orderId.toString());
            if (ObjectUtil.isNotNull(payMap)) return payMap;
            // 2. 根据 id 获取订单信息
            OrderInfo order = orderService.getById(orderId);
            // 3. 保存交易记录
            paymentService.savePaymentInfo(order, PaymentTypeEnum.WEIXIN.getStatus());
            // 4. 设置请求参数
            HashMap<String, String> paramMap = new HashMap<>();
            // 公众账号ID
            paramMap.put("appid", wxPayConfig.getAppId());
            // 商户号
            paramMap.put("mch_id", wxPayConfig.getPartner());
            // 随机字符串
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
            String body = order.getReserveDate() + "就诊" + order.getDepname();
            // 商品描述
            paramMap.put("body", body);
            // 商户订单号
            paramMap.put("out_trade_no", order.getOutTradeNo());
            //paramMap.put("total_fee", order.getAmount().multiply(new BigDecimal("100")).longValue()+"");
            // 标价金额，单位为分
            paramMap.put("total_fee", "1");
            // 终端IP
            paramMap.put("spbill_create_ip", "127.0.0.1");
            // 通知地址
            paramMap.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify");
            // 交易类型
            paramMap.put("trade_type", "NATIVE");
            // 5. 访问统一下单接口
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            // 6. client设置参数
            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap, wxPayConfig.getPartnerKey()));
            client.setHttps(true);
            client.post();
            //7、返回第三方的数据
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            //8、封装返回结果集
            Map map = new HashMap<>();
            map.put("orderId", orderId);
            map.put("totalFee", order.getAmount());
            map.put("resultCode", resultMap.get("result_code"));
            // 前台根据该参数生成二维码
            map.put("codeUrl", resultMap.get("code_url"));
            if (null != resultMap.get("result_code")) {
                //微信支付二维码2小时过期，可采取2小时未支付取消订单
                redisTemplate.opsForValue().set(orderId.toString(), map, 1000, TimeUnit.MINUTES);
            }
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return new HashMap<>();
        }
    }

    //实现方法
    @Override
    public Map queryPayStatus(Long orderId, String paymentType) {
        try {
            OrderInfo orderInfo = orderService.getById(orderId);
            //1、封装参数
            Map paramMap = new HashMap<>();
            // 公众账号ID
            paramMap.put("appid", wxPayConfig.getAppId());
            // 商户号
            paramMap.put("mch_id", wxPayConfig.getPartner());
            // 商户订单号
            paramMap.put("out_trade_no", orderInfo.getOutTradeNo());
            // 随机字符串
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
            //2、设置请求
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap, wxPayConfig.getPartnerKey()));
            client.setHttps(true);
            client.post();
            //3、返回第三方的数据，转成Map
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            //4、返回
            return resultMap;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 1. 根据订单 id 查询支付记录
     * 2. 根据支付记录创建退款记录
     * 3. 访问微信申请退款接口
     * 4. 申请退款成功后，更新退款记录，返回 true
     * 5. 申请退款失败，返回 false
     * @param orderId
     * @return
     */
    @Override
    public Boolean refund(Long orderId) {
        try {
            PaymentInfo paymentInfoQuery = paymentService.getPaymentInfo(orderId, PaymentTypeEnum.WEIXIN.getStatus());

            RefundInfo refundInfo = refundInfoService.saveRefundInfo(paymentInfoQuery);
            if (refundInfo.getRefundStatus().intValue() == RefundStatusEnum.REFUND.getStatus().intValue()) {
                return true;
            }
            Map<String, String> paramMap = new HashMap<>(8);
            // 公众账号ID
            paramMap.put("appid", wxPayConfig.getAppId());
            // 商户号
            paramMap.put("mch_id", wxPayConfig.getPartner());
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
            // 微信订单号
            paramMap.put("transaction_id", paymentInfoQuery.getTradeNo());
            // 商户订单编号
            paramMap.put("out_trade_no", paymentInfoQuery.getOutTradeNo());
            // 商户退款单号
            paramMap.put("out_refund_no", "tk" + paymentInfoQuery.getOutTradeNo());
            //       paramMap.put("total_fee",paymentInfoQuery.getTotalAmount().multiply(new BigDecimal("100")).longValue()+"");
            //       paramMap.put("refund_fee",paymentInfoQuery.getTotalAmount().multiply(new BigDecimal("100")).longValue()+"");
            paramMap.put("total_fee", "1");
            paramMap.put("refund_fee", "1");
            String paramXml = WXPayUtil.generateSignedXml(paramMap, wxPayConfig.getPartnerKey());
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/secapi/pay/refund");
            client.setXmlParam(paramXml);
            client.setHttps(true);
            // 设置证书
            client.setCert(true);
            // 证书密码即是商户号
            client.setCertPassword(wxPayConfig.getPartner());
            client.post();
            // 返回第三方的数据
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            // SUCCESS 退款申请接收成功，结果通过退款查询接口查询
            // FAIL 提交业务失败
            if (WXPayConstants.SUCCESS.equalsIgnoreCase(resultMap.get("result_code"))) {
                refundInfo.setCallbackTime(DateTime.now());
                refundInfo.setTradeNo(resultMap.get("refund_id"));
                refundInfo.setRefundStatus(RefundStatusEnum.REFUND.getStatus());
                refundInfo.setCallbackContent(JSONObject.toJSONString(resultMap));
                refundInfoService.updateById(refundInfo);
                return true;
            }
            return false;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
